package com.spark.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spark.common.core.Result;
import com.spark.common.query.QueryGenerator;
import com.spark.modules.system.entity.SysRolePermission;
import com.spark.modules.system.entity.params.RoleAuthParams;
import com.spark.modules.system.service.ISysRolePermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 系统角色权限Controller
 *
 * @author LYCHEE
 * @date 2025/02/18 10:17
 */
@RestController
@RequestMapping(value = "/sys/rolePermission")
public class SysRolePermissionController {

    @Resource
    private ISysRolePermissionService sysRolePermissionService;

    /**
     * 分页列表查询
     *
     * @param sysRolePermission  系统角色权限对象
     * @param pageNo   分页
     * @param pageSize 分页
     * @return 系统角色权限列表
     */
    @GetMapping(value = "/queryPageList")
    public Result<?> queryPageList(SysRolePermission sysRolePermission,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SysRolePermission> queryWrapper = QueryGenerator.initQueryWrapper(sysRolePermission);
        Page<SysRolePermission> page = new Page<SysRolePermission>(pageNo, pageSize);
        IPage<SysRolePermission> pageList = sysRolePermissionService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 列表查询
     *
     * @param sysRolePermission 系统角色权限对象
     * @return 系统角色权限列表
     */
    @GetMapping(value = "/queryList")
    public Result<?> queryList(SysRolePermission sysRolePermission) {
        QueryWrapper<SysRolePermission> queryWrapper = QueryGenerator.initQueryWrapper(sysRolePermission);
        List<SysRolePermission> list = sysRolePermissionService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统角色权限对象
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam String id) {
        SysRolePermission sysRolePermission = sysRolePermissionService.getById(id);
        if (Objects.isNull(sysRolePermission)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(sysRolePermission);
    }

    /**
     * 新增
     *
     * @param sysRolePermission 系统角色权限对象
     * @return 成功或失败
     */
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysRolePermission sysRolePermission) {
        boolean save = sysRolePermissionService.save(sysRolePermission);
        return Result.flag(save);
    }

    /**
     * 编辑
     *
     * @param sysRolePermission 系统角色权限对象
     * @return 成功或失败
     */
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysRolePermission sysRolePermission) {
        boolean update = sysRolePermissionService.updateById(sysRolePermission);
        return Result.flag(update);
    }

    /**
     * 通过id删除
     *
     * @param id 主键
     * @return 成功或失败
     */
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") String id) {
        boolean update = sysRolePermissionService.removeById(id);
        return Result.flag(update);
    }

    /**
     * 通过id批量删除删除
     *
     * @param ids 主键
     * @return 成功或失败
     */
    @DeleteMapping(value = "/deleteBatchByIds/{ids}")
    public Result<?> deleteBatchByIds(@PathVariable(name = "ids") String[] ids) {
        boolean update = sysRolePermissionService.removeBatchByIds(Arrays.asList(ids));
        return Result.flag(update);
    }

    /**
     * 根据角色ID查询权限
     * @param roleId 角色ID
     * @return
     */
    @GetMapping(value = "/queryAuthByRoleId")
    public Result<?> queryAuthByRoleId(@RequestParam String roleId){
        LambdaQueryWrapper<SysRolePermission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRolePermission::getRoleId, roleId);
        List<SysRolePermission> sysRolePermissions = sysRolePermissionService.list(lambdaQueryWrapper);
        List<String> ids = sysRolePermissions.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
        return Result.ok(ids);
    }

    /**
     * 角色授权
     * @return 成功失败
     */
    @PreAuthorize("@sp.hasPerm('sys:role:auth')")
    @PostMapping(value = "/authRole")
    public Result<?> authRole(@Validated @RequestBody RoleAuthParams authParams){
        String roleId = authParams.getRoleId();
        if (CollectionUtils.isEmpty(authParams.getAuthIds())){
            // 取消角色权限
            sysRolePermissionService.delAll(roleId);
        }else {
            // 取消角色权限
            sysRolePermissionService.delAll(roleId);
            for (String authId : authParams.getAuthIds()) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(authId);
                sysRolePermissionService.save(rolePermission);
            }
        }
        return Result.ok("授权成功");
    }

}
